// 云函数入口文件
const cloud = require('wx-server-sdk')
const base64 = require('base-64')
const CryptoJS = require("crypto-js")

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const appId = '' // 填写大模型APPID
const apiSecret = '' // 填写大模型APISecret
const apiKey = '' // 填写大模型APIKey
const host = 'spark-api.xf-yun.com'
const date = new Date().toUTCString()
const get = '/v4.0/chat'
const algorithm = 'hmac-sha256'
const headers = 'host date request-line'

const tmp = `host: ${host}\ndate: ${date}\nGET ${get} HTTP/1.1`
const tmp_sha = CryptoJS.HmacSHA256(tmp, apiSecret)
const signature = CryptoJS.enc.Base64.stringify(tmp_sha)
const authorization_origin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`
const authorization = base64.encode(authorization_origin)
const url = `wss://${host}${get}?authorization=${authorization}&date=${encodeURI(date)}&host=${host}`

// 云函数入口函数
exports.main = async (event, context) => {
  return { appId, url }
}